# demo03_pickle.py
import pickle
userdb = {"name": "zhangsan", "age": 18}
fw = open("/opt/user.data", mode="wb")
pickle.dump(userdb, fw)  # 将userdb字典写入文件
fw.close()
# with:
# with open("/opt/user.data", mode="wb") as fw:
#     pickle.dump(userdb, fw)

# 读取字典数据
fr = open("/opt/user.data", mode="rb")
result = pickle.load(fr)  # 读取字典数据,将字典数据赋值给result
print(result)  # {'name': 'zhangsan', 'age': 18}
print(type(result))  # <class 'dict'>
print(result["name"], result["age"])  # zhangsan 18
fr.close()
